import cgi
import datetime
import urllib
import wsgiref.handlers
import os


from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

class Link(db.Model):
    submitter=db.StringProperty()
    title=db.StringProperty()
    link=db.StringProperty(multiline=True)
    date=db.DateTimeProperty(auto_now_add=True)

def linkbook_key(linkbook_name=None):
    return db.Key.from_path('Linkbook', linkbook_name or 'default_linkbook')

class MainPage(webapp.RequestHandler):
    def get(self):
        linkbook_name=self.request.get('linkbook_name')

        links_query=Link.all().ancestor(linkbook_key(linkbook_name)).order('-date')
        links=links_query.fetch(10)

        if users.get_current_user():
            url= users.create_logout_url(self.request.uri)
            url_linktext= 'Logout'
        else:
            url= users.create_login_url(self.request.uri)
            url_linktext= 'Login'

        template_values= {
            'links': links,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

        
class Linkbook(webapp.RequestHandler):
    def post(self):
        linkbook_name= self.request.get('linkbook_name')
        link=Link(parent=linkbook_key(linkbook_name))

        if users.get_current_user():
            link.submitter=users.get_current_user().nickname()

        link.title= self.request.get('title')
        link.link = self.request.get('content')
        link.put()
        self.redirect('/?'+urllib.urlencode({'linkbook_name': linkbook_name}))

application = webapp.WSGIApplication(
                                    [('/', MainPage),
                                     ('/submit', Linkbook)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
